import functools
import logging
from operator import and_

from flask import session, g


def user_login_data(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 获取到当前登录用户的id
        user_id = session.get("user_id")
        # 通过id获取用户信息
        user = None
        if user_id:
            from info.models import User
            try:
                user = User.query.get(user_id)
            except Exception as e:
                logging.error("Mysql数据库异常,异常原因%s"%e)
                user = None

        g.user = user
        return f(*args, **kwargs)
    return wrapper

def admin_login_data(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 获取到当前登录用户的id
        admin_id = session.get("admin_id")
        # 通过id获取用户信息
        admin = None
        if admin_id:
            from info.models import User
            try:
                admin = User.query.filter(and_(User.id==admin_id,User.is_admin==True)).all()
                if admin:
                    admin = admin[0]
                else:
                    admin = None
            except Exception as e:
                logging.error("Mysql数据库异常,异常原因%s"%e)
                admin = None

        g.admin = admin
        return f(*args, **kwargs)
    return wrapper

def do_index_class(index):
    """自定义过滤器，过滤点击排序html的class"""
    if index == 1:
        return "first"
    elif index == 2:
        return "second"
    elif index == 3:
        return "third"
    else:
        return ""